package com.zidian.teacher.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zidian.teacher.R;
import com.zidian.teacher.application.MyApplication;
import com.zidian.teacher.utils.CommonDialogUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import greenDAO.bean.Course;
import greenDAO.bean.StudyWeek;
import greenDAO.dao.CourseDao;
import greenDAO.dao.DaoMaster;
import greenDAO.dao.DaoSession;
import greenDAO.dao.StudyWeekDao;
import okhttp3.Call;
import com.zidian.teacher.activity.CourseMessageActivity;
import com.zidian.teacher.bean.StudyCourseTable;
import com.zidian.teacher.common.BaseFragment;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.utils.GetUserInfo;
import com.zidian.teacher.utils.ToastUtil;
import com.zidian.teacher.view.ClassInfo;
import com.zidian.teacher.view.ScheduleView;
import com.zidian.teacher.wheel.NumericWheelAdapter;
import com.zidian.teacher.wheel.WheelView;

/**
 * className：
 * 作者：xjc on 2016/8/21 11:32
 * 邮箱：1475977630@qq.com
 */
public class CourseFragment extends BaseFragment {


    public AlertDialog mDialogView;
    private ImageView menu;

    private TextView weekSetting;
    private WheelView weekCount;
    private TextView mBtnDateConfirm;
    private TextView mBtnCancel;
    private DaoSession daoSession;
    public SQLiteDatabase db;
    public DaoMaster.DevOpenHelper helper;
    public DaoMaster daoMaster;
    private ArrayList<ClassInfo> classList;
    private ArrayList<StudyCourseTable.DataBean> dataList = new ArrayList<>();
    private ScheduleView scheduleView;
    private int currentWeek = 1;

    @Override
    protected void initView(View view, Bundle savedInstanceState) {

        weekSetting = (TextView) view.findViewById(R.id.course_week);
        scheduleView = (ScheduleView) view.findViewById(R.id.scheduleView);
        daoSession = ((MyApplication) getActivity().getApplication()).getDaoSession();
        StudyWeekDao weekDao = daoSession.getStudyWeekDao();
        CourseDao coursedao = daoSession.getCourseDao();
        List<Course> courseList = coursedao.queryBuilder()
                .where(CourseDao.Properties.TeacherId.eq(GetUserInfo.getTeacherId(mActivity))).list();
        List<StudyWeek> weekList = weekDao.queryBuilder().list();

        if (courseList.size() == 0) {
            try {
                getCourseTable();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            if (weekList.size() == 0) {
                weekSetting.setText("请选择周次");
            } else {
                weekSetting.setText("第" + weekList.get(0).getWeek() + "周");
                getClassData();
                scheduleView.setClassList(classList);
            }
        }

        weekSetting.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                clickBirthday();
            }
        });

        scheduleView.setOnItemClassClickListener(new ScheduleView.OnItemClassClickListener() {

            @Override
            public void onClick(ClassInfo classInfo) {

//                ToastUtil.showToast(mActivity.getApplication(), "您点击的课程是：" + classInfo.getClassname() + classInfo.getBeginEndWeek() + classInfo.getClassRoom());

                ArrayList<String> list = new ArrayList<>();
                list.add(classInfo.getClassname());
                list.add(classInfo.getClassRoom());
                list.add(classInfo.getBeginEndWeek());
                list.add(classInfo.getCourseWeeklyId());
                list.add(classInfo.getCourseId());

                Intent intent = new Intent();
                intent.setClass(mActivity.getApplicationContext(), CourseMessageActivity.class);
                intent.putStringArrayListExtra("classMessage", list);
                mActivity.startActivity(intent);
            }
        });


    }

    public static CourseFragment newInstance() {
        return new CourseFragment();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.tab_fargment_course;
    }

    /**
     * 选择周
     */
    private void clickBirthday() {
        mDialogView = CommonDialogUtil.getCommonDialog(getActivity(),
                R.layout.item_course_week, Gravity.BOTTOM);

        weekCount = (WheelView) mDialogView.findViewById(R.id.id_week);
        mBtnDateConfirm = (TextView) mDialogView.findViewById(R.id.btn_confirm);
        mBtnCancel = (TextView) mDialogView.findViewById(R.id.btn_cancel);
        mBtnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialogView.dismiss();
            }
        });
        mBtnDateConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectedResult();
            }
        });
        setUpDataDate();
    }

    /**
     * 更新日期数据
     **/
    private void setUpDataDate() {
        getDataPick();
        weekCount.setVisibleItems(7);

    }

    private void getDataPick() {
        StudyWeekDao weekDao = daoSession.getStudyWeekDao();
        List<StudyWeek> weekList = weekDao.queryBuilder().list();
        int curYear = 1;
        if (weekList.size() > 0) {
            curYear = weekList.get(0).getWeek();
        } else {
            curYear = 1;

        }
        NumericWheelAdapter numericWheelAdapter1 = new NumericWheelAdapter(
                getActivity(), 1, 24);
        numericWheelAdapter1.setLabel("周");
        weekCount.setViewAdapter(numericWheelAdapter1);
        weekCount.setCyclic(true);
        weekCount.setCurrentItem(curYear - 1);

    }

    /**
     * 显示最后的时间和地址的结果
     */
    private void showSelectedResult() {
        int curWeek = weekCount.getCurrentItem() + 1;
        Log.e("c", currentWeek + "  " + curWeek);
        if (currentWeek != curWeek) {
            currentWeek = curWeek;
            weekSetting.setText("第" + curWeek + "周");
            Calendar cal = Calendar.getInstance();
            int weekIndex = cal.get(Calendar.WEEK_OF_YEAR);
            StudyWeek week = new StudyWeek(null, curWeek, weekIndex);
            daoSession = ((MyApplication) getActivity().getApplication()).getDaoSession();
            StudyWeekDao weekDao = daoSession.getStudyWeekDao();
            weekDao.deleteAll();
            weekDao.insert(week);
            getClassData();
            scheduleView.setClassList(classList);
        }
        mDialogView.dismiss();
    }


    /**
     * 通过接口获取到课程信息  理论上一次获取后除非清除数据 不然不会调用
     *
     * @throws IOException
     */
    private void getCourseTable() throws IOException {
        String loginUrl = Constant.URL_GOAL + "course/select";

        Map<String, String> map = new HashMap<>();
        map.put("teacherId", GetUserInfo.getTeacherId(mActivity));
        map.put("token", GetUserInfo.getToken(mActivity));


        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("T", e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                Gson gson = new Gson();

                Log.e("T", response);

                StudyCourseTable data = gson.fromJson(response, StudyCourseTable.class);
                if (data.isSuccess()) {
                    DaoSession daoSession = ((MyApplication) getActivity().getApplication()).getDaoSession();
                    CourseDao coursedao = daoSession.getCourseDao();
                    dataList.addAll(data.getData());
                    for (int i = 0; i < dataList.size(); i++) {
                            Course course = new Course();
                            course.setId(null);
                            course.setClassRoom(dataList.get(i).getClassRoom());
                            course.setCourseId(dataList.get(i).getCourseId());
                            course.setCourseLength(getClassLength(dataList.get(i).getWeeklyQuarter()));
                            course.setTeacherId(GetUserInfo.getTeacherId(mActivity));
                            course.setWeeklyDay(getWeekDay(dataList.get(i).getWeeklyDay()));
                            course.setWeeklyQuarter(getBeginClass(dataList.get(i).getWeeklyQuarter()));
                            course.setWeek(Integer.parseInt(dataList.get(i).getBeginEndWeek()));
                            course.setCourseName(dataList.get(i).getCourseName());
                            course.setBeginEndWeek(dataList.get(i).getBeginEndWeek());
                            course.setCourseWeeklyId(dataList.get(i).getCourseWeeklyId() + "");

                            coursedao.insertOrReplace(course);
                    }
                    getClassData();
                    scheduleView.setClassList(classList);// 将课程信息导入到课表中
                }
            }
        });
    }


    /**
     * @param myclass
     * @return 通过字符串获取上课的长度即连续上课的节数
     */
    private int getClassLength(String myclass) {
        if (myclass.lastIndexOf(",") != -1) {
            String c = myclass.substring(myclass.lastIndexOf(",") + 1, myclass.length());
            String b = myclass.substring(0, myclass.indexOf(","));
            int i = Integer.parseInt(b);
            int j = Integer.parseInt(c);
            return j - i + 1;
        } else {
            return 1;
        }

    }


    /**
     * @param weeklyDay
     * @return 通过字符串 转化为上课星期几  返回int型数据
     */
    private int getWeekDay(String weeklyDay) {

        int day = 1;

        if (weeklyDay.equals("周一")) {
            day = 1;
        } else if (weeklyDay.equals("周二")) {
            day = 2;
        } else if (weeklyDay.equals("周三")) {
            day = 3;
        } else if (weeklyDay.equals("周四")) {
            day = 4;
        } else if (weeklyDay.equals("周五")) {
            day = 5;
        } else if (weeklyDay.equals("周六")) {
            day = 6;
        } else if (weeklyDay.equals("周日")) {
            day = 7;
        }
        return day;

    }

    /**
     * @param myclass
     * @return 转化第一节课的时间
     */
    private int getBeginClass(String myclass) {
        if (myclass.indexOf(",") == -1) {
            return Integer.parseInt(myclass);
        } else {
            String b = myclass.substring(0, myclass.indexOf(","));
            int i = Integer.parseInt(b);
            return i;
        }
    }

    /**
     * 从数据库中获取当前周的课程信息
     */
    private void getClassData() {
        DaoSession daoSession = ((MyApplication) getActivity().getApplication()).getDaoSession();
        CourseDao coursedao = daoSession.getCourseDao();
        StudyWeekDao weekDao = daoSession.getStudyWeekDao();

        Calendar cal = Calendar.getInstance();
        int weekIndex = cal.get(Calendar.WEEK_OF_YEAR);


        List<StudyWeek> weekList = weekDao.queryBuilder().list();
        int curWeek = 1;
        if (weekList.size() == 0) {
            curWeek = 1;
        } else {
            curWeek = weekList
                    .get(0).getWeek() + weekIndex - weekList.get(0).getTime();
//            Log.e("INDEX", weekList
//                    .get(0).getWeek() + "");
        }


        List<Course> courseList = coursedao.queryBuilder()
                .where(CourseDao.Properties.Week.eq(curWeek))
                .orderAsc(CourseDao.Properties.Id)
                .build().list();


        classList = new ArrayList<ClassInfo>();
        for (int i = 0; i < courseList.size(); i++) {
            ClassInfo classInfo = new ClassInfo();
            classInfo.setClassname(courseList.get(i).getCourseName());
            classInfo.setFromClassNum(courseList.get(i).getWeeklyQuarter());
            classInfo.setClassNumLen(courseList.get(i).getCourseLength());
            classInfo.setClassRoom(courseList.get(i).getClassRoom());
            classInfo.setWeekday(courseList.get(i).getWeeklyDay());
            classInfo.setBeginEndWeek(courseList.get(i).getBeginEndWeek());
            classInfo.setCourseId(courseList.get(i).getCourseId());
            classInfo.setCourseWeeklyId(courseList.get(i).getCourseWeeklyId());
            classList.add(classInfo);
        }

    }

}
